

#include "linklist.h"

/**
 *  生产者生产，生产以后在头后面插入，
 *     生产者生产了到20个数据，结束子线程
 *      50ms生产一次
 * 
 *   消费者删除头后面节点， 
 *      80ms消费一次
 */

pthread_mutex_t lock;
list_pnode head = NULL;
int linklist_len = 0;

void *producer(void *arg)
{
	list_pnode new_pnode;
	//初始化单向链表
	init_linklist(&head);
	while(1) {
		new_pnode = (list_pnode)malloc(sizeof(list_node));
		if (NULL==new_pnode) return NULL; 
		new_pnode->data = rand() % 100 + 1;
		printf("produce %d\n", new_pnode->data);
		//头插
		pthread_mutex_lock(&lock);
		insert_linklist(head, new_pnode);
		linklist_len++;
		printf("produce linklist len=%d\n", linklist_len);
		show_linklist(head);
		if (linklist_len == 20) {
			pthread_mutex_unlock(&lock);
			break;
		}else
			pthread_mutex_unlock(&lock);
		usleep(500000);
	}
	
	pthread_exit(0);
}

void *consumer(void *arg)
{
	list_pnode temp;
	while (1) {
		pthread_mutex_lock(&lock);
		if (head->next == NULL) {
			pthread_mutex_unlock(&lock);
			
		} else {
			temp = head->next;
			printf("consumer %d\n", temp->data);
			del_linklist(head);
			linklist_len--;
			show_linklist(head);
			printf("consumer linklist len=%d\n", linklist_len);
			pthread_mutex_unlock(&lock);
		}
		usleep(800000);
	}
	
	
	pthread_exit(0);
}


int main(void)
{
	pthread_t pid, cid;
	srand(time(NULL)); //随机种子
	pthread_mutex_init(&lock, NULL);
	pthread_create(&pid, NULL, producer, NULL);
	pthread_create(&cid, NULL, consumer, NULL);
	pthread_join(pid, NULL);
	pthread_join(cid, NULL);
	pthread_mutex_destroy(&lock);
	return 0;
}


